package mo.offer_special;

import java.util.ArrayList;
import java.util.List;

public class L085 {

    private List<String> res = new ArrayList<>();

    public List<String> generateParenthesis(int n) {
        doGenerate(new StringBuilder(), 0, 0, n);
        return res;
    }

    private void doGenerate(StringBuilder builder, int left, int right, int n) {
        if (builder.length() == n * 2) {
            res.add(new String(builder));
            return;
        }

        if (left < n) {
            builder.append('(');
            doGenerate(builder, left + 1, right, n);
            builder.deleteCharAt(builder.length()-1);
        }

        if (left < right) {
            builder.append(')');
            doGenerate(builder, left, right+1, n);
            builder.deleteCharAt(builder.length()-1);
        }
    }

}
